package org.example.rsy.service.impl;

import org.example.rsy.service.BaseTikaService;
import org.springframework.stereotype.Service;
import org.xml.sax.ContentHandler;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

@Service
public class StructuredTextTikaService extends BaseTikaService {

    private final StringWriter writer = new StringWriter();

    @Override
    public ContentHandler initHandler() {
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler;
        try {
            handler = factory.newTransformerHandler();
            handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
            handler.setResult(new StreamResult(writer));
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        }
        return handler;
    }

    @Override
    public String extractData() {
        String string = writer.toString();
        writer.getBuffer().setLength(0);
        return string;
    }

    @Override
    public int getCode() {
        return 5;
    }
}
